package xin.alum.aim.rabbitmq;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import xin.alum.aim.constant.AimConstant;
import xin.alum.aim.constant.Constants;
import xin.alum.aim.groups.ClusterFactory;
import xin.alum.aim.groups.Session;
import xin.alum.aim.model.Pusher;
import xin.alum.aim.model.Transportable;
import xin.alum.aim.util.JSONUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

class RabbitMQPusher implements ClusterFactory {

    protected final InternalLogger logger =
            InternalLoggerFactory.getInstance(this.getClass());
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private <T> boolean push(String channel, T d) {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.getHeaders().put("desc", "信息描述..");
        messageProperties.getHeaders().put("type", "消息类型：" + d.getClass().getName());
        Message message = new Message(JSONUtils.toJSONByte(d), messageProperties);
        rabbitTemplate.convertAndSend(channel, message);
        return true;
    }

    @Override
    public void kick(Session session) {
        push(Constants.BIND_MESSAGE_INNER_QUEUE, session);
    }

    @Override
    public void push(String recipient, Transportable data) {
        switch (data.getTag()) {
            case AimConstant.DATA_TYPE_REPLY:
                push(Constants.EVENT_MESSAGE_INNER_QUEUE, new Pusher(recipient, data));
                break;
            case AimConstant.DATA_TYPE_MESSAGE:
                push(Constants.PUSH_MESSAGE_INNER_QUEUE, new Pusher(recipient, data));
                break;
            default:
                logger.error("无效Type类型：{}", data);
                break;
        }
    }
}
